<!--
author:        hejiyang <silentmanager@163.com>
date:          2024-11-23 21:59:09
component:     orderEmit
Copyright © YourCompanyName All rights reserved
-->
<template>
  <el-dialog
    :destroy-on-close="true"
    title="编辑订单信息"
    v-model="isVisible"
    @close="handleClose"
    width="800px"
  >
    <FormComponent :rules="rules" :config="formConfig" ref="formRef" />
    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
      <el-button type="primary" :loading="loading" @click="handleSave">保存</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch, defineProps, defineEmits } from 'vue'
import FormComponent from '@/components/FormComponent/index.vue'
import { updateOrderInfo, UpdateOrderInfoReq } from '@/api/order/all'

const message = useMessage() // 消息弹窗

// 定义组件的 props
interface Props {
  visible: boolean
  emitData: UpdateOrderInfoReq
}

// 获取 props 和 emits
const props = defineProps<Props>()
const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void // 添加 success 事件
}>()

// ==================== 表单  ====================
const loading = ref(false)
const formRef = ref<InstanceType<typeof FormComponent>>()
const rules = {
  customerName: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
  address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
  customerPhone: [{ required: true, message: '请输入客户手机', trigger: 'blur' }]
}
const formConfig = [
  {
    label: '客户名称',
    prop: 'customerName',
    type: 'input',
    options: { placeholder: '请输入客户名称' }
  },
  {
    label: '详细地址',
    prop: 'address',
    type: 'input',
    options: { placeholder: '请输入详细地址' }
  },
  {
    label: '客户手机',
    prop: 'customerPhone',
    type: 'input',
    options: { placeholder: '请输入客户手机' }
  }
]
// 保存备注的处理函数
const handleSave = async () => {
  try {
    loading.value = true
    //@ts-ignore
    await formRef.value.formRef?.validate()
    const res = await updateOrderInfo({
      ...props.emitData,
      ...formRef.value?.formData
    })
    if (res.code === 0) {
      loading.value = false
      message.success('保存成功')
      emit('success')
      handleClose()
    }
  } catch (e) {
    loading.value = false
    console.error(e)
  }
}
// ==================== 弹窗  ====================
// 局部状态变量，用于管理弹窗的可见性
const isVisible = ref<boolean>(props.visible)

// 监视 props.visible 的变化，以更新局部状态
watch(
  () => props.visible,
  async (newValue) => {
    isVisible.value = newValue
    if (newValue) {
      // 弹窗显示时，将 emitData 更新到表单中
      await nextTick() // 等待 DOM 更新
      formRef.value?.setData(props.emitData) // 调用表单组件的 setData 方法
    }
  }
)

// 关闭弹窗的处理函数
const handleClose = () => {
  isVisible.value = false // 设置局部状态
  emit('update:visible', false) // 通知父组件
}
</script>

<style scoped>
/* 您的样式 */
</style>
